
package com.bear.cmcc.NetTestHTTP.service;

import com.bear.cmcc.NetTestHTTP.component.PowerLock;
import com.bear.cmcc.NetTestHTTP.component.json.respond.AppUpdateRespond;
import com.bear.cmcc.NetTestHTTP.constant.HttpConstant;
import com.bear.cmcc.NetTestHTTP.constant.MyCommonConstant;
import com.bear.cmcc.NetTestHTTP.util.SetUtil;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import java.io.File;

/**
 * 更新并下载APK文件
 * 
 * @author suchangjun
 */
public class NetUpdateVersionService extends Service {

    private static final String TAG = "NetUpdateVersionService";

    public static final String ISDOWN = "isdown";

    private PowerLock powerLock;

    private Context context;

    private String type;

    private boolean isdown;// 是否检查过了版本状态

    /**
     * 检查版本
     */
    private Runnable checkVersionRunnable = new Runnable() {

        @Override
        public void run() {
            String service_Description = "";
            if (MyCommonConstant.PrivateActionName.SERVICE_DOWNAPK_TYPE_FJ.equals(type)) {
                try {
                    String[] localVersion = SetUtil.getLocalVersion(context);
                    // String[] serviceVersion =
                    // SetUtil.getServiceVersion_FJ(context);
                    AppUpdateRespond serviceVersion = SetUtil.getServiceVersion_FJAdapter(context);
                    if (localVersion != null && serviceVersion != null
                            && serviceVersion.getErrorCode() == HttpConstant.CODE_SUCCESS
                            && serviceVersion.getVersionInfo() != null) {
                        // 本地的版本号
                        String local_versionName = localVersion[1];
                        // 服务器的版本号
                        String service_versionName = serviceVersion.getVersionInfo()
                                .getVersionName();
                        if (!local_versionName.equals(service_versionName)&&service_versionName!=null&&!service_versionName.trim().equals("")) {
                            // 需要更新版本
                            service_Description = serviceVersion.getVersionInfo().getLog();// 更新信息
                            sendUpdateBroad(
                                    MyCommonConstant.PrivateActionName.NET_WORK_APK_DATA_DOWN_TYPE_CHECK,
                                    MyCommonConstant.PrivateActionName.NET_WORK_APK_ISUPDATE_YES,
                                    service_Description, serviceVersion.getVersionInfo().getUrl());
                        } else {
                            // 已是最新版本
                            sendUpdateBroad(
                                    MyCommonConstant.PrivateActionName.NET_WORK_APK_DATA_DOWN_TYPE_CHECK,
                                    MyCommonConstant.PrivateActionName.NET_WORK_APK_ISUPDATE_NO,
                                    "1", null);
                        }
                    } else {
                        // 取版本失败
                        sendUpdateBroad(
                                MyCommonConstant.PrivateActionName.NET_WORK_APK_DATA_DOWN_TYPE_CHECK,
                                MyCommonConstant.PrivateActionName.NET_WORK_APK_ISUPDATE_NO, "0",
                                null);
                    }
                } catch (Exception e) {
                    if (e != null) {
                        e.printStackTrace();
                    }
                    // 取版本失败
                    sendUpdateBroad(
                            MyCommonConstant.PrivateActionName.NET_WORK_APK_DATA_DOWN_TYPE_CHECK,
                            MyCommonConstant.PrivateActionName.NET_WORK_APK_ISUPDATE_NO, "0", null);
                }
            } else {
                // 集团
                try {
                    String[] localVersion = SetUtil.getLocalVersion(context);
                    String[] serviceVersion = SetUtil.getServiceVersion(context);
                    if (localVersion != null && serviceVersion != null) {
                        // 本地的版本号
                        String local_versionName = localVersion[1];
                        // 服务器的版本号
                        String service_versionName = serviceVersion[0];
                        if (!local_versionName.equals(service_versionName)
                                && (service_versionName != null && !service_versionName.trim()
                                        .equals(""))) {
                            // 需要更新版本
                            service_Description = serviceVersion[2];// 更新信息
                            sendUpdateBroad(
                                    MyCommonConstant.PrivateActionName.NET_WORK_APK_DATA_DOWN_TYPE_CHECK,
                                    MyCommonConstant.PrivateActionName.NET_WORK_APK_ISUPDATE_YES,
                                    service_Description, null);
                        } else {
                            sendUpdateBroad(
                                    MyCommonConstant.PrivateActionName.NET_WORK_APK_DATA_DOWN_TYPE_CHECK,
                                    MyCommonConstant.PrivateActionName.NET_WORK_APK_ISUPDATE_NO,
                                    "1", null);
                        }
                    } else {
                        // 更新失败
                        sendUpdateBroad(
                                MyCommonConstant.PrivateActionName.NET_WORK_APK_DATA_DOWN_TYPE_CHECK,
                                MyCommonConstant.PrivateActionName.NET_WORK_APK_ISUPDATE_NO, "0",
                                null);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    // 更新失败
                    sendUpdateBroad(
                            MyCommonConstant.PrivateActionName.NET_WORK_APK_DATA_DOWN_TYPE_CHECK,
                            MyCommonConstant.PrivateActionName.NET_WORK_APK_ISUPDATE_NO, "0", null);
                }
            }

        }

    };

    /**
     * 下载APK线程
     */
    // private Runnable downApkRunnable = new DownRunable();

    class DownThread extends Thread {

        private String url = null;

        public DownThread(String url) {
            super();
            this.url = url;
        }

        @Override
        public void run() {
            String downStatus = MyCommonConstant.PrivateActionName.ALL_APK_DOWNSTATUS_NO;
            try {
                // 下载APK文件
                if (MyCommonConstant.PrivateActionName.SERVICE_DOWNAPK_TYPE_FJ.equals(type)) {
                    // downStatus = SetUtil.getDownServiceAPKStaus_FJ(context);
                    File file = SetUtil.downloadFile(context, url);

                    if (file != null && file.exists() && file.isFile() && file.canRead()) {
                        downStatus = MyCommonConstant.PrivateActionName.ALL_APK_DOWNSTATUS_YES;

                    } else {
                        downStatus = MyCommonConstant.PrivateActionName.ALL_APK_DOWNSTATUS_NO;
                    }

                } else {
                    downStatus = SetUtil.getDownServiceAPKStaus(context);
                }
                Log.d(TAG, "updateAPKService-success:" + downStatus);
            } catch (Exception e) {
                if (e != null) {
                    e.printStackTrace();
                }
                Log.d(TAG, "updateAPKService-Exception:" + e.getMessage());
            } finally {
                sendUpdateBroad(
                        MyCommonConstant.PrivateActionName.NET_WORK_APK_DATA_DOWN_TYPE_DOWN,
                        MyCommonConstant.PrivateActionName.NET_WORK_APK_ISUPDATE_YES, downStatus,
                        null);
                stopSelf();// 数据下载完成，把自己这个服务停止。
                if (powerLock != null) {
                    powerLock.releaseWakeLock();
                }
            }

        }
    };

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public void onCreate() {
        super.onCreate();
        try {
            powerLock = new PowerLock(this, "NetUpdateVersionService");
            this.context = this;
            Log.d(TAG, "updateAPKService-onCreate");
        } catch (Exception e) {
            if (e != null) {
                Log.d(TAG, "updateAPKService-onCreate-Exception:" + e.getMessage());
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onStart(Intent intent, int startId) {
        Log.d(TAG, "updateAPKService-onStart");
        if (intent == null)
            return;

        type = intent.getStringExtra(MyCommonConstant.PrivateActionName.SERVICE_DOWNAPK_TYPE);
        isdown = intent.getBooleanExtra(ISDOWN, false);
        String downUrl = intent.getStringExtra(MyCommonConstant.PrivateActionName.ALL_APK_DOWN_URL);

        if (isdown) {
            startDownFile(downUrl);
        } else {
            startCheckVersion();
        }
        super.onStart(intent, startId);
    }

    /**
     * 启动一个线程检查版本
     */
    private void startCheckVersion() {
        if (powerLock != null) {
            powerLock.acquireWakeLock();
        }
        Thread thread = new Thread(checkVersionRunnable);
        thread.start();
    }

    /**
     * 启动一个下载文件进程。
     * 
     * @param context
     */
    private void startDownFile(String downUrl) {
        Log.d(TAG, "updateAPKService-startDownFile11");
        if (powerLock != null) {
            powerLock.acquireWakeLock();
        }
        Thread thread = new DownThread(downUrl);
        thread.start();
    }

    /**
     * 文件下载完成发送一个广播通知activity.
     * 
     * @param broadType 广播类型:NET_WORK_APK_DATA_DOWN_TYPE_CHECK:
     *            检查版本,NET_WORK_APK_DATA_DOWN_TYPE_DOWN: 下载APK
     * @param updateStatus 版本是否需要版本
     * @param downStatus 是否下载apk成功
     */
    private void sendUpdateBroad(String broadType, String updateStatus, String downStatus,
            String url) {
        Intent intent = new Intent(MyCommonConstant.PrivateActionName.NET_WORK_APK_DATA_DOWN);
        // 发送广播类型
        intent.putExtra(MyCommonConstant.PrivateActionName.NET_WORK_APK_DATA_DOWN_TYPE, broadType);
        // 发送是否需要更新的状态
        intent.putExtra(MyCommonConstant.PrivateActionName.NET_WORK_APK_ISUPDATE, updateStatus);
        // 发送下载APK的状态
        intent.putExtra(MyCommonConstant.PrivateActionName.ALL_APK_DOWNSTATUS, downStatus);

        intent.putExtra(MyCommonConstant.PrivateActionName.ALL_APK_DOWN_URL, url);
        sendBroadcast(intent);
    }

    public void onDestroy() {
        try {
            if (powerLock != null) {
                powerLock.releaseWakeLock();
            }
            powerLock = null;
        } catch (Exception e) {
            if (e != null) {
                e.printStackTrace();
            }
        }
        super.onDestroy();
    }

}
